<?php
App::uses('AppController', 'Controller');
App::uses('Paypal', 'Paypal.Lib');
App::uses('CakeNumber', 'Utility');
/**
 * Users Controller
 *
 * @property User $User
 * @property PaginatorComponent $Paginator
 */
class UsersController extends AppController {

/**
 * Components
 *
 * @var array
 */
	public $Paypal;
	public $components = array('Paginator');
	public $theme = 'BackEnd';
	public $layout = 'admin';
/**
 * count template method
 *
 * @return array
 */
	private function _counttem($time){
		if($time == 'day'){
			$sqlSelectCount ="SELECT count(*) as count 
								FROM templates 
								WHERE DATE(created) = DATE(NOW())";
	        $result = $this->User->Template->query($sqlSelectCount);
	        return $result;
		}

		if($time == 'week'){
			$sqlSelectCount ="SELECT count(*) as count 
								FROM templates 
								WHERE WEEKOFYEAR(created) = WEEKOFYEAR(NOW())
								AND MONTH(created) = MONTH(NOW()) 
        						AND YEAR(created) = YEAR(NOW())";
	        $result = $this->User->Template->query($sqlSelectCount);
	        return $result;
		}

		if($time == 'month'){
			$sqlSelectCount ="SELECT count(*) as count 
								FROM templates 
								WHERE MONTH(created) = MONTH(NOW()) 
        						AND YEAR(created) = YEAR(NOW())";
	        $result = $this->User->Template->query($sqlSelectCount);
	        return $result;
		}

		if($time == 'year'){
			$sqlSelectCount ="SELECT count(*) as count 
								FROM templates 
								WHERE YEAR(created) = YEAR(NOW())";
	        $result = $this->User->Template->query($sqlSelectCount);
	        return $result;
		}

		if($time == 'all'){
			$sqlSelectCount ="SELECT count(*) as count 
								FROM templates";
	        $result = $this->User->Template->query($sqlSelectCount);
	        return $result;
		}

		else{
			$data = explode("-", $time);
			if(checkdate($data[1], $data[0], $data[1])){
				$sqlSelectCount ="SELECT count(*) as count 
									FROM templates 
									WHERE DATE(created) = '".$data[1]."-".$data[2]."-".$data[0]."'";
		        $result = $this->User->Template->query($sqlSelectCount);
		        return $result;
			}
		}
		
		
	}
/**
 * count user method
 *
 * @return array
 */	
	private function _countuse($time){
		if($time == 'day'){
			$sqlSelectCount ="SELECT count(*) as count 
								FROM users 
								WHERE DATE(created) = DATE(NOW())";
	        $result = $this->User->query($sqlSelectCount);
	        return $result;
		}

		if($time == 'week'){
			$sqlSelectCount ="SELECT count(*) as count 
								FROM users 
								WHERE WEEKOFYEAR(created) = WEEKOFYEAR(NOW())
								AND MONTH(created) = MONTH(NOW()) 
        						AND YEAR(created) = YEAR(NOW())";
	        $result = $this->User->query($sqlSelectCount);
	        return $result;
		}

		if($time == 'month'){
			$sqlSelectCount ="SELECT count(*) as count 
								FROM users 
								WHERE MONTH(created) = MONTH(NOW()) 
        						AND YEAR(created) = YEAR(NOW())";
	        $result = $this->User->query($sqlSelectCount);
	        return $result;
		}

		if($time == 'year'){
			$sqlSelectCount ="SELECT count(*) as count 
								FROM users 
								WHERE YEAR(created) = YEAR(NOW())";
	        $result = $this->User->query($sqlSelectCount);
	        return $result;
		}
		if($time == 'all'){
			$sqlSelectCount ="SELECT count(*) as count 
								FROM users";
	        $result = $this->User->query($sqlSelectCount);
	        return $result;
		}

		else{
			$data = explode("-", $time);
				if(checkdate($data[1], $data[0], $data[2])){
					$sqlSelectCount ="SELECT count(*) as count 
									FROM users 
									WHERE DATE(created) = '".$data[2]."-".$data[1]."-".$data[0]."'";
		        $result = $this->User->query($sqlSelectCount);
		        return $result;
		    }
		}
        
	}
/**
 * count pricing method
 *
 * @return array
 */
	private function _countpricing($time){
		if($time == 'day'){
			$sqlSelectCount ="SELECT count(*) as count 
								FROM subscriptions_users 
								WHERE DATE(start_date) = DATE(NOW())";
	        $result = $this->User->Subscription->query($sqlSelectCount);
	        return $result;
		}
        if($time == 'week'){
        	$sqlSelectCount ="SELECT count(*) as count 
        						FROM subscriptions_users 
        						WHERE WEEKOFYEAR(start_date) = WEEKOFYEAR(NOW()) 
        						AND MONTH(start_date) = MONTH(NOW()) 
        						AND YEAR(start_date) = YEAR(NOW())";
	        $result = $this->User->Subscription->query($sqlSelectCount);
	        return $result;

		}

		if($time == 'month'){
			$sqlSelectCount ="SELECT count(*) as count 
        						FROM subscriptions_users 
        						WHERE MONTH(start_date) = MONTH(NOW()) 
        						AND YEAR(start_date) = YEAR(NOW())";
	        $result = $this->User->Subscription->query($sqlSelectCount);
	        return $result;
		}

		if($time == 'year'){
			$sqlSelectCount ="SELECT count(*) as count 
        						FROM subscriptions_users 
        						WHERE YEAR(start_date) = YEAR(NOW())";
	        $result = $this->User->Subscription->query($sqlSelectCount);
	        return $result;
		}

		if($time == 'all'){
			$sqlSelectCount ="SELECT count(*) as count 
        						FROM subscriptions_users";
	        $result = $this->User->Subscription->query($sqlSelectCount);
	        return $result;
		}
		else{
			$data = explode("-", $time);
				if(checkdate($data[1], $data[0], $data[2])){
					$sqlSelectCount ="SELECT count(*) as count 
								FROM subscriptions_users 
								WHERE DATE(start_date) = '".$data[2]."-".$data[1]."-".$data[0]."'";
			        $result = $this->User->Subscription->query($sqlSelectCount);
			        return $result;
		    }
		}
	}
/**
 * count revanue method
 *
 * @return array
 */
	private function _countrevanue($time){
		if($time == 'day'){
			$query = "SELECT sum(payment) as revenue 
						FROM subscriptions_users 
						WHERE DATE(start_date) = DATE(NOW())";
	        $result = $this->User->Subscription->query($query);
	        return $result;
		}
		
        if($time == 'week'){
        	$query = "SELECT sum(payment) as revenue 
        				FROM subscriptions_users 
        				WHERE WEEKOFYEAR(start_date) = WEEKOFYEAR(NOW()) 
        				AND MONTH(start_date) = MONTH(NOW())
        				AND YEAR(start_date) = YEAR(NOW())";
	        $result = $this->User->Subscription->query($query);
	        return $result;
		}

		if($time == 'month'){
			$query = "SELECT sum(payment) as revenue 
						FROM subscriptions_users 
						WHERE MONTH(start_date) = MONTH(NOW())
        				AND YEAR(start_date) = YEAR(NOW())";
	        $result = $this->User->Subscription->query($query);
	        return $result;
		}

		if($time == 'year'){
			$query = "SELECT sum(payment) as revenue 
						FROM subscriptions_users 
						WHERE YEAR(start_date) = YEAR(NOW())";
	        $result = $this->User->Subscription->query($query);
	        return $result;
		}

		if($time == 'all'){
			$query = "SELECT sum(payment) as revenue 
						FROM subscriptions_users";
	        $result = $this->User->Subscription->query($query);
	        return $result;
		}

		else{
			$data = explode("-", $time);
				if(checkdate($data[1], $data[0], $data[2])){
					$sqlSelectCount ="SELECT sum(payment) as revenue  
								FROM subscriptions_users 
								WHERE DATE(start_date) = '".$data[1]."-".$data[2]."-".$data[0]."'";
			        $result = $this->User->Subscription->query($sqlSelectCount);
			        return $result;
		    }
		}
	}

	public function admin_dashboard(){
        //count template in day
        $this->set('countTemplate', $this->_counttem('day'));
        //end cout template in day
        //count all pricing in day
        $this->set('countPricing',$this->_countpricing('day'));

        $this->set('countUser', $this->_countuse('day'));
        $allPricing = $this->_countpricing('all');
        $allPricing = $allPricing[0][0]["count"];
        $this->set('allPricing',$allPricing);
        //end count all user 
        //count user free
        $options['joins'] = array(
			    array('table' => 'subscriptions_users',
			        'alias' => 'sub_u',
			        'type' => '',
			        'conditions' => array(
			            'sub_u.subscription_id = Subscription.id', 'Subscription.name'=> 'Free'
			        )
			    )
			);
        $result = $this->User->Subscription->find('count',$options);
        $this->set('countFree',$result);
        //end count user free
        //count user use monthly
        $options['joins'] = array(
			    array('table' => 'subscriptions_users',
			        'alias' => 'sub_u',
			        'type' => '',
			        'conditions' => array('sub_u.end_date >=' => date('Y-m-d h:i:s', strtotime('0 month')),
			            'sub_u.subscription_id = Subscription.id', 'Subscription.name'=> 'Month'
			        )
			    )
			);
        $result = $this->User->Subscription->find('count',$options);
        $this->set('countMonth',$result);
        //end count user user month
        //count user use yearly
        $options['joins'] = array(
			    array('table' => 'subscriptions_users',
			        'alias' => 'sub_u',
			        'type' => '',
			        'conditions' => array('sub_u.end_date >=' => date('Y-m-d h:i:s', strtotime('0 year')),
			            'sub_u.subscription_id = Subscription.id', 'Subscription.name'=> 'Year'
			        )
			    )
			);
        $result = $this->User->Subscription->find('count',$options);
        $this->set('countYear',$result);
        //end count user use yearly
        //count all has been expiration
        $options['joins'] = array(
			    array('table' => 'subscriptions_users',
			        'alias' => 'sub_u',
			        'type' => '',
			        'conditions' => array('sub_u.end_date <' => date('Y-m-d h:i:s', strtotime('0 year')),
			            'sub_u.subscription_id = Subscription.id')
			    ));
        $result = $this->User->Subscription->find('count',$options);
        $resultExpi = ($result/$allPricing)*100;
        $this->set('resultExpi',$resultExpi);
        //count all user use free not eapiration
         $options['joins'] = array(
			    array('table' => 'subscriptions_users',
			        'alias' => 'sub_u',
			        'type' => '',
			        'conditions' => array('sub_u.end_date >=' => date('Y-m-d h:i:s', strtotime('0 year')),
			            'sub_u.subscription_id = Subscription.id','Subscription.name' =>'Free')
			    ));
        $result = $this->User->Subscription->find('count',$options);
        //% userFree
        $resultFree = ($result/$allPricing)*100;
        $this->set('resultFree',$resultFree);
        //end %userFree
         //count all user use yearly not eapiration
         $options['joins'] = array(
			    array('table' => 'subscriptions_users',
			        'alias' => 'sub_u',
			        'type' => '',
			        'conditions' => array('sub_u.end_date >=' => date('Y-m-d h:i:s', strtotime('0 year')),
			            'sub_u.subscription_id = Subscription.id','Subscription.name'=> 'Year ')
			    ));
        $result = $this->User->Subscription->find('count',$options);
        //%userYearly
        $resultYear = ($result/$allPricing )*100;
        $this->set('resultYear',$resultYear);
        //end % userYearly
        //count user monthly and not expiration
        $options['joins'] = array(
			    array('table' => 'subscriptions_users',
			        'alias' => 'sub_u',
			        'type' => '',
			        'conditions' => array('sub_u.end_date >=' => date('Y-m-d h:i:s', strtotime('0 year')),
			            'sub_u.subscription_id = Subscription.id', 'Subscription.name'=> 'Month'
			        )
			    )
			);
        $userMonth = $this->User->Subscription->find('count',$options);
        //% userMonth
        $resultMonth = ($userMonth/$allPricing)*100;
        $this->set('resultMonth',$resultMonth);
        //end userMonthly
        //sum Revenue
        $this->set('revenueAll',$this->_countrevanue('all'));
        //end sum revenue
        //sum Revenue in day
        $query = "SELECT sum(payment) as revenue FROM subscriptions_users WHERE DATE(start_date)= DATE(NOW())";
        $revenueInday = $this->User->Subscription->query($query);
        $this->set('revenueInday',$revenueInday);
        //end sum revenue in day
        //sum revenue in Yesterday
        $query = "SELECT sum(payment) as revenue FROM subscriptions_users WHERE  DATE(NOW()) - DATE(start_date) = 1";
        $revenueInyesterday =  $this->User->Subscription->query($query);;
        $this->set('revenueInyesterday',$revenueInyesterday);
        //end sum revenue in yesterday
        //sum revenue in monday 
        $query = "SELECT sum(payment) as revenue FROM subscriptions_users WHERE DAYNAME(start_date) = 'Monday' AND WEEKOFYEAR(start_date) = WEEKOFYEAR(NOW())";
        $revenueInMon = $this->User->Subscription->query($query);
        $this->set('revenueInMon',$revenueInMon);
        //end sum revenue in monday
        //sum revenue in Friday
        $query = "SELECT sum(payment) as revenue FROM subscriptions_users WHERE DAYNAME(start_date) = 'Friday' AND WEEKOFYEAR(start_date)=WEEKOFYEAR(NOW())";
        $revenueInFri = $this->User->Subscription->query($query);
        $this->set('revenueInFri',$revenueInFri);
        //end sum revenue in Friday
        //sum revenue in Thursday
        $query = "SELECT sum(payment) as revenue FROM subscriptions_users WHERE DAYNAME(start_date) = 'Thursday' AND WEEKOFYEAR(start_date)=WEEKOFYEAR(NOW())";
        $revenueInThur = $this->User->Subscription->query($query);
        $this->set('revenueInThur',$revenueInThur);
        //end sum revernue in Thursday
        //sum revenue in Wednesday
        $query = "SELECT sum(payment) as revenue FROM subscriptions_users WHERE DAYNAME(start_date) = 'Thursday' AND WEEKOFYEAR(start_date)=WEEKOFYEAR(NOW())";
        $revenueInWed = $this->User->Subscription->query($query);
        $this->set('revenueInWed',$revenueInWed);
        //end sum revenue in Wednesday
        //sum revenue in Tuesday
        $query = "SELECT sum(payment) as revenue FROM subscriptions_users WHERE DAYNAME(start_date) = 'Tuesday' AND WEEKOFYEAR(start_date)=WEEKOFYEAR(NOW())";
        $revenueInTue = $this->User->Subscription->query($query);
        $this->set('revenueInTue',$revenueInTue);
        //end revenue in Tuesday
        //count template used most
        $query = "SELECT me_tem1.template_id 
				        FROM medefiles_templates AS me_tem1 
				        GROUP BY me_tem1.template_id 
				        HAVING COUNT(me_tem1.id) >= (SELECT MAX(me_tem2.number) 
						        							FROM (SELECT DISTINCT count(id) AS 'number' 
						        								FROM medefiles_templates GROUP BY template_id) as me_tem2)";
		$id_temp = $this->User->Template->query($query);
		$options = array('conditions' => array('Template.' . $this->User->Template->primaryKey => $id_temp[0]["me_tem1"]["template_id"]));
		$resultTemp = $this->User->Template->find('all', $options);
		//end count template used most
		//select user has most template
		$query = "SELECT tem1.user_id
						FROM templates AS tem1
						GROUP BY tem1.user_id
						HAVING COUNT(tem1.id) >= (SELECT MAX(tem2.number)
														FROM (SELECT DISTINCT COUNT(id) AS 'number'
																	FROM templates
																	GROUP BY user_id) AS tem2)";
		$id_user = $this->User->query($query);
		$this->User->recursive = -1;
		$options = array('conditions' => array('User.'.$this->User->primaryKey => $id_user[0]["tem1"]["user_id"]));
		$resultUser = $this->User->find('first',$options);
		//end select user has most template 

		//select top template free used most
		$query = "SELECT tem.name, tem.id, tem.user_id, med_tem.soluong , u.username
					FROM templates as tem, (SELECT template_id, COUNT(*) AS 'soluong' 
					                        FROM medefiles_templates 
					                        WHERE medefile_id IN (SELECT id  
	                												FROM medefiles 
	                												WHERE user_id IN (SELECT distinct user_id 
	                																	FROM subscriptions_users 
	                																	WHERE subscription_id IN (SELECT id  
            																									   FROM subscriptions  
            																									   WHERE name like 'Free')) 
																	AND types like 'svg')  
																	GROUP BY template_id) AS med_tem, 
					users as u
					WHERE tem.id = med_tem.template_id
					AND tem.user_id = u.id
					ORDER BY med_tem.soluong DESC
					LIMIT 10";
		$result = $this->User->query($query);
		$this->set('topTemFrees',$result);
		//end select top template free used
		//select top template monthly used
		$query = "SELECT tem.name, tem.id, tem.user_id, med_tem.soluong ,u.username
					FROM templates as tem, (SELECT template_id, COUNT(*) AS 'soluong' 
					                        FROM medefiles_templates 
					                        WHERE medefile_id IN (SELECT id  
	                												FROM medefiles 
	                												WHERE user_id IN (SELECT distinct user_id 
	                																	FROM subscriptions_users 
	                																	WHERE subscription_id IN (SELECT id  
            																									   FROM subscriptions  
            																									   WHERE name like 'Month')) 
																	AND types like 'svg')  
																	GROUP BY template_id) AS med_tem ,
					users as u
					WHERE tem.id = med_tem.template_id
					AND tem.user_id = u.id
					ORDER BY med_tem.soluong DESC
					LIMIT 10";
		$result = $this->User->query($query);
		$this->set('topTemMonths',$result);
		//end select template monthly used
		//select top template yearly use
		$query = "SELECT tem.name, tem.id, tem.user_id, med_tem.soluong , u.username
					FROM templates as tem, (SELECT template_id, COUNT(*) AS 'soluong' 
					                        FROM medefiles_templates 
					                        WHERE medefile_id IN (SELECT id  
	                												FROM medefiles 
	                												WHERE user_id IN (SELECT distinct user_id 
	                																	FROM subscriptions_users 
	                																	WHERE subscription_id IN (SELECT id  
            																									   FROM subscriptions  
            																									   WHERE name like 'Year')) 
																	AND types like 'svg')  
																	GROUP BY template_id) AS med_tem ,
						 users as u
					WHERE tem.id = med_tem.template_id
					AND tem.user_id = u.id
					ORDER BY med_tem.soluong DESC
					LIMIT 10";
		$result = $this->User->query($query);
		// var_dump($result);
		// die();
		$this->set('topTemYears',$result);
		//end select top template yearly use
		//select top template be utilized 
		$query = "SELECT tem.name, tem.id, tem.user_id, med_tem.soluong, (med_tem.soluong/med_tem.phantram) *100 AS 'phantram' 
					FROM templates as tem, (SELECT template_id, COUNT(*) AS 'soluong', sub_med.total AS 'phantram'
					                                FROM medefiles_templates AS med_tem, (SELECT COUNT(*) as 'total'
					                                										FROM medefiles_templates) AS sub_med
					                                WHERE medefile_id IN (SELECT id 
					                                                      FROM medefiles 
					                                                      WHERE types like 'svg') 
					                                GROUP BY template_id) AS med_tem 
					WHERE tem.id = med_tem.template_id ORDER BY med_tem.soluong DESC LIMIT 20";
		$result = $this->User->query($query);
		$this->set('topTemplates',$result);
		//end select top template be utilized 
		// var_dump($result);
		// die();
	}

/**
* ajax requesrt
*
*
*/
	public function getInfo($act = null){
		$this->layout = '';
			// var_dump($act);
			// $data = explode("-", $act);
			// var_dump($data);
			// die();
			$this->set('countTemplate', $this->_counttem($act));

	        $this->set('countUser', $this->_countuse($act));

	        $this->set('countPricing',$this->_countpricing($act));

	        $this->set('revenueAll',$this->_countrevanue($act));
	}

	// public function getInfo(){
	// 	$this->layout = '';
	// 	if($this->request->is('POST')){
	// 		$result =$this->_countpricing('all');
	// 		echo $result;
	// 		die();
	// 	}
	// 	die();
	// }
/**
 * index method
 *
 * @return void
 */
	public function admin_index() {
		$this->User->recursive = 0;
		
		$this->Paginator->settings = array(
			'conditions' => array('User.id NOT LIKE' => 3),
			'limit' => 10
		);
		
		$users = $this->Paginator->paginate('User');
	
		$this->set('users', $users);
	}

/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function admin_view($id = null) {
		if (!$this->User->exists($id)) {
			throw new NotFoundException(__('Invalid user'));
		}
		$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
		$this->set('user', $this->User->find('first', $options));
	}

/**
 * add method
 *
 * @return void
 */
	public function admin_add() {
		if ($this->request->is('post')) {
			$this->User->create();
			if ($this->User->save($this->request->data)) {
				$this->Session->setFlash(__('The user has been saved.'));
				return $this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
			}
		}
		$groups = $this->User->Group->find('list', array('conditions' => array('Group.id NOT LIKE' => 3)));
		$subscriptions = $this->User->Subscription->find('list');
		$this->set(compact('groups', 'subscriptions'));
	}

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function admin_edit($id = null) {
		if (!$this->User->exists($id)) {
			throw new NotFoundException(__('Invalid user'));
		}
		if ($this->request->is(array('post', 'put'))) {
			if ($this->User->save($this->request->data)) {
				$this->Session->setFlash(__('The user has been saved.'));
				return $this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
			}
		} else {
			$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
			$this->request->data = $this->User->find('first', $options);
		}
		$groups = $this->User->Group->find('list', array('conditions' => array('Group.id NOT LIKE' => 3)));
		$subscriptions = $this->User->Subscription->find('list');
		$this->set(compact('groups', 'subscriptions'));
	}

/**
 * delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function admin_delete($id = null) {
		$this->User->id = $id;
		if (!$this->User->exists()) {
			throw new NotFoundException(__('Invalid user'));
		}
		$this->request->allowMethod('post', 'delete');
		if ($this->User->delete()) {
			$this->Session->setFlash(__('The user has been deleted.'));
		} else {
			$this->Session->setFlash(__('The user could not be deleted. Please, try again.'));
		}
		return $this->redirect(array('action' => 'index'));
	}
	
/**
 * index method
 *
 * @return void
 */
	public function admin_customers_index() {
	
		$this->User->recursive = 1;
		
		$this->Paginator->settings = array(
			'conditions' => array('User.group_id' => 3),
			'limit' => 10
		);
		
		$users = $this->Paginator->paginate('User');
		$this->set('users', $users);
	}
	
/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function admin_customers_view($id = null) {
		if (!$this->User->exists($id)) {
			throw new NotFoundException(__('Invalid user'));
		}
		$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
		$this->set('user', $this->User->find('first', $options));
	}
	
/**
 * add method
 *
 * @return void
 */
	public function admin_customers_add() {
		if ($this->request->is('post')) {
			$this->User->create();
			$subscription_id = $this->request->data['Subscription']['Subscription'];
			$options = 	array(
				'conditions' => array('Subscription.id' => $subscription_id), 
				'recursive' => 1,
				'fields' => array('Subscription.price', 'Subscription.expiration'),
				'limit' => 1
			);
			$subscription = $this->User->Subscription->find('first', $options);

			$payment = $subscription['Subscription']['price'];
			$expiration = $subscription['Subscription']['expiration'];
			$start_date = date("Y-m-d");
			$end_date = date("Y-m-d", strtotime("+ {$expiration} day"));
			
			if ($this->User->save($this->request->data)) {
				$user_id = $this->User->id;
				$options = 	array(
					'fields' => array('SubscriptionsUser.id'),
					'limit' => 1,
					'order' => array('SubscriptionsUser.id DESC'),
				);
				
				$SubscriptionsUser = $this->User->SubscriptionsUser->find('first', $options);
				$SubscriptionsUser_id = $SubscriptionsUser['SubscriptionsUser']['id'];
				
				$data = array(
					'SubscriptionsUser' => array(
						'start_date' => $start_date,
						'end_date' => $end_date,
						'user_id' => $user_id,
						'subscription_id' => $subscription_id,
						'payment' => $payment,
						'id' => $SubscriptionsUser_id
					)
				);
				if($this->User->SubscriptionsUser->save($data)){
					$this->Session->setFlash(__('The user has been saved.'));
					return $this->redirect(array('action' => 'customers_add'));
				}
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
			}
		}
		$groups = $this->User->Group->find('list', array('conditions' => array('Group.id' => 3)));
		$subscriptions = $this->User->Subscription->find('list');
		$this->set(compact('groups', 'subscriptions'));
	}
	
/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function admin_customers_edit($id = null) {
		if (!$this->User->exists($id)) {
			throw new NotFoundException(__('Invalid user'));
		}
		if ($this->request->is(array('post', 'put'))) {
			if ($this->User->save($this->request->data)) {
				$this->Session->setFlash(__('The user has been saved.'));
				return $this->redirect(array('action' => 'customer_index'));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
			}
		} else {
			$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
			$this->request->data = $this->User->find('first', $options);
		}
		$groups = $this->User->Group->find('list', array('conditions' => array('Group.id' => 3)));
		$subscriptions = $this->User->Subscription->find('list');
		$this->set(compact('groups', 'subscriptions'));
	}
	
/**
 * delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function admin_customers_delete($id = null) {
		
		$this->User->id = $id;
		
		if (!$this->User->exists()) {
			throw new NotFoundException(__('Invalid user'));
		}
		
		if ($this->User->delete()) {
			$this->Session->setFlash(__('The user has been deleted.'));
		} else {
			$this->Session->setFlash(__('The user could not be deleted. Please, try again.'));
		}
		
		return $this->redirect(array('action' => 'customers_index'));
	}
	
	public function admin_customers_security($user_id){
		$this->admin_security($user_id);
		$this->render('admin_security');
	}
	
	public function admin_login(){
		$this->layout = 'login';
		if ($this->request->is('post')) {
			if ($this->Auth->login()) {
				return $this->redirect(array('controller' => 'users', 'action' => 'index'));
			}
			$this->Session->setFlash(__('Your username or password was incorrect.'), 'default', array('class' => 'alert alert-danger'));
		}
	}
	
	public function admin_logout(){
		$this->redirect( $this->Auth->logout() );	
	}
	
	public function beforeFilter() {
		parent::beforeFilter();
		$this->Paypal = new Paypal(array(
			'sandboxMode' => true,
			'nvpUsername' => 'hoangfreelance-facilitator_api1.gmail.com',
			'nvpPassword' => '1392434709',
			'nvpSignature' => 'AVp9qCHAgbnkiUjUqamJB9VgTXVAAQZM75kDZgfzGFtavga.HG7SerYO',
		));
		 $this->Auth->allow();
	}
	
	public function admin_security($user_id){
		
		$aro = new Aro();
		$aro_record = $aro->findByAlias('User:'.$user_id);
		
		if(!empty($aro_record)){
			$aro_alias = $aro_record['Aro']['alias'];
		}
		
		if(isset($_POST['action']) && $_POST['action'] == 'security'){
			
			$access_type = $_POST['access'];
			$aco_id = $_POST['id'];
			
			$aco = new Aco();
			$aco_record = $aco->findById($aco_id);
			
			if($access_type == "allow"){
				$this->Acl->allow($aro_alias, $aco_record['Aco']['alias']);
			} elseif($access_type == "deny"){
				$this->Acl->deny($aro_alias, $aco_record['Aco']['alias']);
			}
			
			die();
		}

		$aco = new Aco();		
		$aco_records = $aco->find('all');
		
		$current_user = $this->User->find('first',array('conditions' => array('User.id' => $user_id)));
		
		$acl = $this->Acl;
		
		$this->set(compact('aco_records','aco', 'aro_alias', 'current_user','acl'));
	}
	
	public function admin_customers_upgrade(){		
		if($_POST['action'] && $_POST['action'] == 'upgrade'){
			$subscritions = $this->User->Subscription->generateTreeList();
			echo(json_encode($subscritions));
			die();
		}
	}

	public function signup(){
		$this->theme = 'FrontEnd';
		$this->layout = 'signup';
		if($this->request->is('post')){
            $s = $this->request->data;
			$site = FULL_BASE_URL . '/' . basename(ROOT) . '/' . $this->params['controller'] . '/';
			$custom = $s["User"]["username"];
			$order = array(
				'description' => 'Your purchase with Acme clothes store',
				'currency' => 'GBP',
				'return' => $site . 'success',
				'cancel' => $site . 'cancel',
				'custom' => $custom,
				'items' => array(
					0 => array(
						'name' => 'Blue shoes',
						'description' => 'A pair of really great blue shoes',
						'tax' => 2.00,
						'shipping' => 0.00,
						'subtotal' => 8,
					),
				)
			);
			
			$this->User->create();
            if($this->User->save($this->request->data)){
            	
					$this->Session->setFlash(__('The user has been saved.'));
					$user_id = $this->User->getLastInsertId();
				} 
			else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
			}
			
            $id = $s['packeage'];
            //var_dump($s);			// Nếu khách hàng chọn gói FREE
            $this->User->SubscriptionsUser->create();
			if($id == 1){
				// Ta sẽ thêm 1 record vào bảng Users_Subscriptions
				

				$start_date = date("Y-m-d");
				$end_date = date("Y-m-d");
				$subdata = array(
					'SubscriptionsUser' => array(
						'start_date' => $start_date,
						'end_date' => $end_date,
						'user_id' => $user_id,
						'payment' => 0
					)
				);
				$this->User->SubscriptionsUser->save($subdata);

			} else {
				try {
					// Tao tai khoan cho user o day roi moi chuyen sang paypal
					return $this->redirect($this->Paypal->setExpressCheckout($order));
				} catch (Exception $e) {
					echo $e->getMessage();
				}  
			}
		}
        
        
	}

	public function cancel(){
		$this->redirect(array('controller'=>'FrontEnd','action' => 'index'));
	}
	
	public function success(){
		try {
			print_r($this->Paypal->getExpressCheckoutDetails($_GET['token'])); die();
			// thêm 1 record vào bảng Users_Subscriptions
		} catch (Exception $e) {
			echo $e->getMessage();
		} 
	}
	
}
